import re

from utils.file_util import FileUtil


class SbsConvertor:
    array_types = ["IRPYRawContainer"]

    def __init__(self, file_path: str) -> None:
        self.lines = FileUtil.read_text_file_lines(file_path)
        self.line_num = 0
        self.content = {}

    def to_json(self) -> dict:
        self.__root()
        return self.content

    def __root(
        self,
    ):
        self.content = {}

        # find first object
        while True:
            line = self.lines[self.line_num]
            if len(line) == 0 or not line.startswith("{"):
                self.line_num += 1
                continue

            break

        self.__next_object(self.content)

    def __next_object(
        self,
        content: dict,
    ) -> bool:
        # print(f"行={self.line_num+1}, __next_object")
        # 文件结束
        if self.line_num >= len(self.lines):
            return False
        line = self.lines[self.line_num].strip()

        while len(line) == 0:
            self.line_num += 1
            if self.line_num >= len(self.lines):
                return False
            line = self.lines[self.line_num].strip()

        # 不是对象
        object_start = line.find("{")
        if object_start == -1:
            return False

        # get object name
        object_type = line[object_start+1:].strip()
        content["_$type"] = object_type
        content["_$line"] = self.line_num
        # print(f"行={self.line_num+1}, 对象={object_type}")
        self.line_num += 1

        # 获取属性
        while self.__next_attribute(content, object_type):
            # get more attributes
            pass

        # 对象结束
        line = self.lines[self.line_num].strip()
        if not line.endswith("}"):
            print(f"错误：对象未正确结束，行={self.line_num+1}, 字符={line}")

        # print(f"行={self.line_num+1}, 对象结束={object_type}")
        self.line_num += 1

        return True

    def __next_attribute(
        self,
        content: dict,
        object_type: str
    ) -> bool:
        line: str = self.lines[self.line_num].lstrip()

        # 对象结束
        if not line.startswith("- ") and not line.startswith("{"):
            return False

        # 获取属性名
        attr_line = self.line_num
        name_start = 2
        attr_name = ""
        value_text = ""
        is_array = False
        if line.startswith("{"):
            attr_name = "elements"
            is_array = True
            value_text = line
            # print(f"行={attr_line+1}, 属性={attr_name}，对象数组")
        else:
            name_end = line.find("=", name_start)
            attr_name = line[name_start: name_end].strip()
            value_text = line[name_end+2:].strip()
            is_array = object_type in self.array_types and attr_name == "value"
        # print(f"行={attr_line+1}, 属性={attr_name}")

        # 获取属性值
        value = self.__get_value(value_text, is_array)
        # print(f"行={attr_line+1}, 属性={attr_name}, 值={value}")

        # if type(value) is str:
        #     print(f"行={attr_line+1}, 属性={attr_name}, 值={value}")

        if content.keys().__contains__(attr_name):
            print(f"错误：属性重复，行={attr_line+1}, 属性={attr_name}")
            return True

        content[attr_name] = value
        return True

    def __get_value(
        self,
        value_text: str,
        is_array: bool
    ) -> any:
        '''
        获取属性值
        当前行在属性名那一行。

        value_text: 属性值文本(第一行)
        '''

        while len(value_text.strip()) == 0:
            self.line_num += 1
            value_text = self.lines[self.line_num].strip()

        # 对象
        if value_text.startswith("{"):
            if is_array:
                # 添加到数组
                content = []
                while True:
                    # print(f"行={self.line_num+1}, 属性值是数组")
                    array_item = {}
                    if not self.__next_object(array_item):
                        break
                    content.append(array_item)

                return content
            else:
                # print(f"行={self.line_num+1}, 属性值是对象")
                content = {}
                self.__next_object(content)
                return content

        # 值
        # 考虑多行值的情况
        while not value_text.endswith(";"):
            # print(f"行={self.line_num+1}, 属性值未正确结束, 值={value_text}", )
            self.line_num += 1
            line = self.lines[self.line_num].rstrip()
            if line.endswith(b"\u0001\u0002\u0003".decode("utf8")):
                line = line[:-3]
                value_text += line
            else:
                value_text += ("\n" + line)

        # TODO: 解析不同类型的值
        # - m_currentLeftTop = 0 0 ; // 复合值
        # - weakCGTime = 10.10.2013::8:30:1; // 时间
        # - _classModifier = Unspecified; // 枚举
        # - _kind = Typedef; // 枚举
        # - _Type = String; // 枚举

        self.line_num += 1
        return value_text
